var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Lists = require("../models/lists")

// 连接MongooseDB数据库
mongoose.connect('mongodb://127.0.0.1:27017/Todo',{useNewUrlParser: true});

mongoose.connection.on("connected", function() {
  console.log("MongoDB connected success.")
});

mongoose.connection.on("error", function() {
  console.log("MongoDB connected fail.")
});

mongoose.connection.on("disconnected", function() {
  console.log("MongoDB disconnected.")
});

// 查询todo列表
router.get('/', function (req, res, next) {
  Lists.find({}, function (err, doc) {
    console.log(doc)
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      });
    } else {
      res.json({
        status: '0',
        msg: '',
        result: {
          count: doc.length,
          data: doc
        }
      })
    }
  })
});

// 添加todo项
router.post('/add', function(req, res, next){
  const item = new Lists({
    id: new Date().getTime(),
    content: req.body.content,
    completed: req.body.completed
  });
  item.save((err, doc) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      });
    } else {
      res.json({
        status: '0',
        msg: 'success',
      })
    }
  });
})

// 删除指定todo项
router.post('/del', function(req, res, next){
  let id = req.body.id
  Lists.remove({id}, (err, docs) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      });
    } else {
      res.json({
        status: '0',
        msg: 'success',
      })
    }
  })
})

// 删除已完成的todo项
router.post('/delCompleted', function(req, res, next){
  Lists.remove({completed: true}, (err, docs) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      });
    } else {
      res.json({
        status: '0',
        msg: 'success',
      })
    }
  })
})

// 更新todo项的complete状态
router.post('/edit', function(req, res, next){
  let { id, completed } = req.body;
  console.log({ id, completed })
  Lists.updateOne({id},{"$set":{completed}}, (err, docs) => {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      });
    } else {
      res.json({
        status: '0',
        msg: 'success',
      })
    }
  });
})

module.exports = router;